package vip.aster.system.service.impl;

import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import vip.aster.framework.security.entity.SecurityUser;
import vip.aster.framework.security.entity.UserDetail;
import vip.aster.sensitive.core.SensitiveService;
import vip.aster.system.service.SysTenantService;
import vip.aster.system.service.SysUserService;
import vip.aster.tenant.utils.TenantUtils;

import java.util.Set;

/**
 * 脱敏服务
 * 默认管理员不过滤
 * 需自行根据业务重写实现
 *
 * @author Aster
 * @since 2024/2/7 18:22
 */
@Service
@AllArgsConstructor
public class SysSensitiveServiceImpl implements SensitiveService {
    private SysTenantService tenantService;

    @Override
    public boolean isSensitive(String roleKey, String perms) {
        if (!SecurityUser.isLogin()) {
            return true;
        }

        // 如果是超级管理员，则不脱敏
        if (SecurityUser.isSuperAdmin()) {
            return false;
        }

        boolean roleExist = StrUtil.isNotBlank(roleKey);
        boolean permsExist = StrUtil.isNotBlank(perms);

        UserDetail userDetail = SecurityUser.getUser();
        assert userDetail != null;
        Set<String> authoritySet = userDetail.getAuthoritySet();
        Set<String> roleCodeSet = userDetail.getRoleCodeSet();

        if (roleExist && permsExist) {
            if (roleCodeSet.contains(roleKey) && authoritySet.contains(perms)) {
                return false;
            }
        } else if (roleExist && roleCodeSet.contains(roleKey)) {
            return false;
        } else if (permsExist && authoritySet.contains(perms)) {
            return false;
        }

        //TODO 启用租户时, 租户管理员是否需要脱敏要根据实际业务来
        if (TenantUtils.isEnable()) {
            // 判断当前用户是否租户管理员
            return !tenantService.isTenantAdmin(userDetail.getId(), TenantUtils.getTenantId());
        }

        return true;
    }
}
